#import "XMPopupView.h"


@implementation XMPopupView

- (instancetype)initWithContentView:(UIView *)contentView
                          scheduler:(FGPopupScheduler *)scheduler {
    if (self = [super initWithFrame:UIScreen.mainScreen.bounds]) {
        _switchBehavior = FGPopupViewSwitchBehaviorLatent;
        _scheduler = scheduler;
        self.backgroundColor = [UIColor xm_colorWithHexString:@"000000" alpha:0.5];
        contentView.center = CGPointMake(kScreenWidth / 2, kScreenHeight / 2);
        [self addSubview:contentView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        [self addGestureRecognizer:tap];
    }
    return self;
}

- (instancetype)initWithContentView:(UIView *)contentView
                           fromView:(UIView *)fromView
                          scheduler:(FGPopupScheduler *)scheduler {
    if (self = [super initWithFrame:UIScreen.mainScreen.bounds]) {
        _switchBehavior = FGPopupViewSwitchBehaviorLatent;
        _scheduler = scheduler;
        _fromView = fromView;
        self.backgroundColor = [UIColor xm_colorWithHexString:@"000000" alpha:0];
        contentView.center = CGPointMake(kScreenWidth / 2, kScreenHeight / 2);
        [self addSubview:contentView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        [self addGestureRecognizer:tap];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
}

- (void)showPopupView {
    if (_fromView == nil) {
        [kWindow addSubview:self];
    } else {
        [_fromView addSubview:self];
    }
}

- (void)dismissPopupView {
    [self removeFromSuperview];
}

- (void)tap:(UITapGestureRecognizer *)tap {
    if (self.touchCallBack) {
        self.touchCallBack();
    } else {
        [self dismissPopupView];
    }
}

- (FGPopupViewSwitchBehavior)popupViewSwitchBehavior {
    return self.switchBehavior;
}

@end
